package com.qh.resourcehub.login;

import com.qh.resourcehub.utils.CasXmlUtil;
import com.qh.resourcehub.utils.HttpClientUtil;
import com.qh.resourcehub.utils.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/cas")
public class CasLoginController {

    // CAS 服务端验证接口地址（替换成气政通的真实地址）
    private static final String CAS_VALIDATE_URL = "https://cas.qzt.gov.cn/cas/serviceValidate";

    // 你系统的登录接口 URL（必须和菜单中配置的一致）
    private static final String SERVICE_URL = "https://your-system.com/cas/casLogin";

    @GetMapping("/casLogin")
    public ResponseEntity<?> casLogin(@RequestParam String ticket, HttpServletResponse response) {
        try {
            // 构建验证 URL
            String validateUrl = CAS_VALIDATE_URL + "?ticket=" + URLEncoder.encode(ticket, "UTF-8") +
                    "&service=" + URLEncoder.encode(SERVICE_URL, "UTF-8");

            // 调用气政通服务端接口
            String xml = HttpClientUtil.doGet(validateUrl);

            // 解析 XML，提取用户信息
            String username = CasXmlUtil.extractUsername(xml);

            if (username != null) {
                // ✅ 登录成功，创建你自己的登录态
                String token = JwtUtil.generateToken(username); // 或创建 session
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("username", username);
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("CAS 票据验证失败");
            }

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("CAS 登录异常：" + e.getMessage());
        }
    }
}
